package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.xgkj.diyiketang.activity.data.PhotoAdapter;
import com.xgkj.diyiketang.data.PhotoInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.ChaKanXiangCeTask;
import com.xgkj.diyiketang.task.ShanChuZhaoPianTask;
import com.xgkj.diyiketang.task.ShangChuanZhaoPianTask;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.xiangce.PhoneMainActivity;
import com.xgkj.diyiketang.util.xiangce.PhotoConstant;
import com.xgkj.diyiketang.util.xiangce.PhotoImageInfo;
import com.xgkj.diyiketang.R;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class MyPhotoActivity extends BaseActivity implements View.OnClickListener {
    private final String TAG = getClass().getSimpleName();
    private Context mContext;
    private TextView uploadBtn;
    private PullToRefreshGridView mGridView;
    private PhotoAdapter mAdapter;
    private PopupWindow popWindow;
    private static final int CAMERA_REQUEST = 0;
    private File mFile;
    private File creameFile;
    private String local_url;
    private static final String CAMERA_FILE = "diyiketang/img";
    private static String endPoint = "http://oss-cn-beijing.aliyuncs.com";
    private static String bucket = "chibo-userphoto";
    File folder;
    int totalSize = 0;
    int alreadySize = 0;
    int xiangceListTaskId = -1;
    int size = 24;
    int pageNo = 1;
    private ArrayList<String> urlList = new ArrayList<String>();
    private static String URL_TAG = "http://chibo-userphoto.img-cn-beijing.aliyuncs.com/";
    public final int MESSAGE_UPLOAD = 1;
    public final int MESSAGE_REFRESH = 2;
    private Handler mHandler;
    private TextView mBack;
    private String userId = "";
    private  OSSCredentialProvider credentialProvider;
    private OSS oss;
    ArrayList<PhotoImageInfo> creamlist = new ArrayList<PhotoImageInfo>();
    private RelativeLayout footLayout;
    private TextView cancelText;
    private Button delBtn;
    private int delTaskId = -1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_photo);
        mContext = this;
        initView();
        folder = EatShowSetting.getInstance(mContext).getDataFolder(CAMERA_FILE);
        mHandler = getMyHandler();
        credentialProvider = new OSSPlainTextAKSKCredentialProvider("3p8ABZbISUNNWKES", "Ry6WHblt1YZIsiEPyk3DPwMQDwvbXP");
        oss = new OSSClient(mContext, endPoint, credentialProvider);
    }

    private void initView() {
        if (getEatShowApp().getmUserInfo() != null){
            userId = getEatShowApp().getmUserInfo().getUserId();
        }
        mBack = (TextView) findViewById(R.id.back);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        footLayout = (RelativeLayout) findViewById(R.id.foot_layout);
        cancelText = (TextView) findViewById(R.id.cancle_text);
        cancelText.setOnClickListener(this);
        delBtn = (Button) findViewById(R.id.delphoto);
        delBtn.setOnClickListener(this);
        footLayout.setVisibility(View.GONE);
        uploadBtn = (TextView) findViewById(R.id.upload_btn);
        uploadBtn.setOnClickListener(this);

        mGridView = (PullToRefreshGridView) findViewById(R.id.photolist);
        mAdapter = new PhotoAdapter(mContext, mGridView);
        mGridView.setAdapter(mAdapter);
        mAdapter.setDelLayoutShow(new PhotoAdapter.showDelLayout() {
            @Override
            public void show() {
                footLayout.setVisibility(View.VISIBLE);
                if (mAdapter.getDelList().size() !=0){
                    delBtn.setEnabled(true);
                }else {
                    delBtn.setEnabled(false);
                }
            }
        });
        mGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                getMyPhotos();
            }
        });
        initPopWindow();
        urlList = EatShowSetting.getInstance(mContext).getPhotoList();
        if (urlList.size() > 0) {
            for (int i = 0; i < urlList.size(); i++) {
                uploadphoto(urlList.get(i));
            }
        }

        pageNo = 1;
        getMyPhotos();
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.popwindow,
                null);
        ((Button) view.findViewById(R.id.takephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.choosephoto)).setOnClickListener(this);
        ((Button) view.findViewById(R.id.cancle)).setOnClickListener(this);
        popWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.upload_btn:
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.takephoto:
                popWindow.dismiss();
                String randomString = (((int) (Math.random() * 1000000)) % 900000 + 100000) + "_"+userId;
                String fileName = "IMG" + System.currentTimeMillis() + randomString + ".jpeg";
                creameFile = new File(folder, fileName);
                Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                camera_intent
                        .putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(creameFile));
                startActivityForResult(camera_intent, CAMERA_REQUEST);
                break;
            case R.id.choosephoto:
                popWindow.dismiss();
                Intent intent = new Intent(mContext, PhoneMainActivity.class);
                startActivityForResult(intent, 300);
                break;
            case R.id.cancle:
                popWindow.dismiss();
                break;
            case R.id.cancle_text:
                footLayout.setVisibility(View.GONE);
                mAdapter.setDel(false);
                mAdapter.notifyDataSetChanged();
                break;

            case R.id.delphoto:
                doDeletePhoto();
                break;
        }
    }

    private void doDeletePhoto(){
        String delphoto = "";
        for (int i=0;i<mAdapter.getDelList().size();i++){
            if (i != mAdapter.getDelList().size()-1) {
                delphoto += mAdapter.getDelList().get(i).getPhotoURL() + ",";
            }else {
                delphoto += mAdapter.getDelList().get(i).getPhotoURL();
            }
        }
        PalLog.e(TAG,"删除的图片："+delphoto);
        ShanChuZhaoPianTask task = new ShanChuZhaoPianTask(delphoto);
        task.addListener(mListener);
        delTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (PhotoConstant.selectImageList.size() > 0) {
            alreadySize = 0;
            PalLog.e(TAG,PhotoConstant.selectImageList.size()+"等待上传的照片");
            totalSize = PhotoConstant.selectImageList.size();
//            for (int i=0;i<PhotoConstant.selectImageList.size();i++){
//            }
            mAdapter.addUploadList(PhotoConstant.selectImageList);
            doUploadImages();
        }
        if (PhotoConstant.selectImageList.size()==0 && creamlist.size()==0){
            mAdapter.addUploadList(new ArrayList<PhotoImageInfo>());
        }
    }

    private void doUploadImages() {
        for (int i = 0; i < PhotoConstant.selectImageList.size(); i++) {
            if (!PhotoConstant.selectImageList.get(i).isUploading()) {
                continue;
            }
            Bitmap bitmap = PhotoConstant.selectImageList.get(i).getBitmap();
            if (bitmap != null) {
                String randomString = (((int) (Math.random() * 1000000)) % 900000 + 100000) + "_"+userId;
                String fileName = "IMG" + System.currentTimeMillis() + randomString + ".jpeg";
                mFile = new File(folder, fileName);
                BufferedOutputStream buf = null;
                try {
                    buf = new BufferedOutputStream(new FileOutputStream(mFile));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                boolean isSuccessed = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, buf);
                asyncPutObjectFromLocalFile(oss, bucket, fileName, mFile.getAbsolutePath(), i);
            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CAMERA_REQUEST:
                if (!creameFile.exists()) {
                    return;
                }
                PhotoImageInfo info = new PhotoImageInfo();
                info.setImagePath(creameFile.getAbsolutePath());

                creamlist.add(info);
                mAdapter.addUploadList(creamlist);
                if (info.getBitmap() != null){
                    BufferedOutputStream bufferedOutputStream = null;

                    try {
                        bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(creameFile));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                    boolean isSuccessed = info.getBitmap().compress(Bitmap.CompressFormat.JPEG,100,bufferedOutputStream);
                    asyncPutObjectFromLocalFile(oss,bucket,creameFile.getName(),creameFile.getAbsolutePath(),1000);
                }
                break;
        }
    }

    private void getMyPhotos() {
        ChaKanXiangCeTask task = new ChaKanXiangCeTask(size, pageNo, "");
        task.addListener(mListener);
        xiangceListTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void uploadphoto(String url) {
//        PalLog.e(TAG,"上传TASK");
        ShangChuanZhaoPianTask task = new ShangChuanZhaoPianTask(url);
        task.addListener(new UploadPhotoListener(mContext, url));
        getEatShowApp().getTaskManager().addTask(task);
    }

    private ShowToastTaskEventListener mListener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == xiangceListTaskId){
                mGridView.onRefreshComplete();
            }else if (taskId == delTaskId){

            }
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == xiangceListTaskId) {
                taskId = -1;
                if (data != null) {
                    List<PhotoInfo> list = (List<PhotoInfo>) data;
                    if (pageNo == 1) {
                        mAdapter.clearData();
                    }
                    mAdapter.updateData(list);
                    mGridView.onRefreshComplete();
                    pageNo = result;
                    if (pageNo == 0) {
                        mGridView.setMode(PullToRefreshBase.Mode.DISABLED);
//                        ToastUtil.showMessage(mContext, R.string.no_more);
                    }else {
                        mGridView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
                    }
                }
            }else if (taskId == delTaskId){
                mAdapter.setDel(false);
                footLayout.setVisibility(View.GONE);
                getFirstPhoto();
            }
        }
    };

    private void refreshUpload(String url) {
        if (PhotoConstant.selectImageList.size()>0) {
            mAdapter.addUploadList(PhotoConstant.selectImageList);
        }
        uploadphoto(url);
    }

    private void getFirstPhoto() {
        PhotoConstant.selectImageList.clear();
        pageNo = 1;
        getMyPhotos();
    }


    private Handler myHandler;

    private Handler getMyHandler() {
        if (myHandler == null) {
            myHandler = new MyHandler(MyPhotoActivity.this);
        }

        return myHandler;
    }

    static class MyHandler extends Handler {
        WeakReference<MyPhotoActivity> activity;

        public MyHandler(MyPhotoActivity myPhotoActivity) {
            super();
            activity = new WeakReference<MyPhotoActivity>(myPhotoActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
//                    PalLog.e(activity.get().TAG,"上传图片");
                    int position = msg.arg1;
                    String url = (String) msg.obj;
                    if (position < PhotoConstant.selectImageList.size()) {
                        PhotoConstant.selectImageList.get(position).setUploading(false);
                    }else if (position ==1000){
                        activity.get().creamlist.clear();
                    }
                    activity.get().refreshUpload(url);
                    break;
                case 2:
//                    PalLog.e(activity.get().TAG,"刷新");
                    activity.get().getFirstPhoto();
                    break;
            }
        }
    }

    class UploadPhotoListener extends ShowToastTaskEventListener {
        private String mUrl;

        public UploadPhotoListener(Context context, String url) {
            super(context);
            mUrl = url;
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            urlList.remove(mUrl);
            if (urlList.size() == 0) {
                EatShowSetting.getInstance(mContext).savePhotoList(urlList);
            }

        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }
    }

    public void asyncPutObjectFromLocalFile(OSS oss, String testBucket, final String testObject, String uploadFilePath, final int position) {
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(testBucket, testObject, uploadFilePath);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
//                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                if (position ==1000){
                    Message message = mHandler.obtainMessage(MESSAGE_UPLOAD, position, 0, URL_TAG + testObject);
                    mHandler.sendMessage(message);
                    mHandler.sendEmptyMessageDelayed(MESSAGE_REFRESH, 2000);
                }else {
                    Message message = mHandler.obtainMessage(MESSAGE_UPLOAD, position, 0, URL_TAG + testObject);
                    mHandler.sendMessage(message);
                    PalLog.e(TAG, "UploadSuccess");
                    alreadySize++;
//                PalLog.e(TAG,alreadySize+"已经上传,总数:"+totalSize);
                    if (alreadySize == totalSize) {
//                    mHandler.sendEmptyMessage(MESSAGE_REFRESH);
                        mHandler.sendEmptyMessageDelayed(MESSAGE_REFRESH, 2000);
                    }
                }
                urlList.add(URL_TAG + testObject);
                File existFile = new File(folder, testObject);
                if (existFile.exists()) {
                    existFile.delete();
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
                alreadySize++;
                if (alreadySize == totalSize) {
                    mHandler.sendEmptyMessage(MESSAGE_REFRESH);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (urlList.size() > 0) {
            EatShowSetting.getInstance(mContext).savePhotoList(urlList);
        }
    }
}
